﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Entity.vo;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.WebControls;

namespace Runda.CMS.Portal.StockManagement
{
    public partial class AccessoryStockIn : BasePage
    {
        public Guid StockInID
        {
            get
            {
                if (hiddenStockInID.Value == string.Empty) return Guid.Empty;
                else return new Guid(hiddenStockInID.Value);
            }
            set
            {
                hiddenStockInID.Value = value.ToString();
           }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                StorckInType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.StorckInType)));
                if (Request.QueryString["POID"] != null)
                {
                    lnkbtnSaveAndNew.Visible = false;
                    string POID = Request.QueryString["POID"];
                    POSToStock(POID);
                    this.po.Visible = false;
                    
                }
                Unit.Text = "只";
                if (Request.QueryString["StockInID"] != null)
                {
                    WsmAccessoryStockInEntity StockInEntity = new SystemBll().Get<WsmAccessoryStockInEntity>(new Guid(Request.QueryString["StockInID"]));
                    StockInID = StockInEntity.StockInID;
                    InstockDate.SelectedDate = StockInEntity.InStockdate;
                    StorckInType.SelectedValue = StockInEntity.StorckInType.ToString();
                    ddlStockinProperty.SelectedValue = StockInEntity.StockinProperty.ToString();
                    BusinessNum.Text = StockInEntity.BusinessNum;
                    lblBillCode.Text = StockInEntity.BillCode;
                    supplyno.Text = StockInEntity.supplyno;
                    Memo.Text = StockInEntity.Memo;
                    employeeGUID.Value = StockInEntity.Operator.ToString();
                    employeeName.Text = new SystemBll().Get<SysUserEntity>(StockInEntity.Operator).UserName;

                    DataTable dt = new StockBll().QueryStockInDetail(StockInID.ToString());
                    gridSubItems.DataSource = dt;
                    gridSubItems.DataBind();
                    link_saveBill.Visible = false;
                }
                else
                {
                    employeeName.Text = base.CurrentUserEntity.UserName;
                    employeeGUID.Value = base.CurrentUserID.ToString();

                    if (Request.QueryString["POID"] != null)
                    {
                        POToStock(Request.QueryString["POID"]);
                    }
                    else
                    {
                        StorckInType.SelectedValue = "3";
                    }
                }
            }
            
        }          
        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            DataTable dt = getDateFromGrid(-1);
            bool isExist = false;
            for (int index = 0; index < dt.Rows.Count;index++ )
            {
                String AccessoryId = dt.Rows[index]["AccessoryID"].ToString();
                if (AccessoryId == hiddenInstrumentID.Value.Trim()) {
                    dt.Rows[index]["Count"] = System.Convert.ToInt32(dt.Rows[index]["Count"]) + System.Convert.ToInt32(accessoryCount.Text.Trim());
                    isExist = true;
                }
            }
            if (!isExist)
            {
                DataRow dr = dt.NewRow();
                dr["AccessoryID"] = hiddenInstrumentID.Value.ToString();
                WsmAccessoryInfoEntity entity = new SystemBll().Get<WsmAccessoryInfoEntity>(new Guid(hiddenInstrumentID.Value));
                dr["AccessoryName"] = entity.AccessoryName;
                dr["AccessoryCompanyNum"] = entity.CompanyInstrumentCode;
                dr["Unit"] = Unit.Text.Trim();
                dr["Count"] = accessoryCount.Text.Trim();
                dr["StockSource"] = ddlStockSource.SelectedValue;
                dt.Rows.Add(dr);
            }
            gridSubItems.DataSource = dt;
            gridSubItems.DataBind();
        }

        private DataTable getDateFromGrid(int  i) {
            DataTable dt = new AccessoryInfo().getAccessoryInfoStructure();
            for (int index = 0; index < gridSubItems.Items.Count; index++)
            {   
                Label AccessoryID = gridSubItems.Items[index].FindControl("AccessoryID") as Label;
                Label AccessoryCompanyNum = gridSubItems.Items[index].FindControl("AccessoryCompanyNum") as Label;
                Label AccessoryName = gridSubItems.Items[index].FindControl("AccessoryName") as Label;
                Label Unit = gridSubItems.Items[index].FindControl("Unit") as Label;
                TextBox Count = gridSubItems.Items[index].FindControl("Count") as TextBox;
                Label StockSource = gridSubItems.Items[index].FindControl("StockSource") as Label;
                Label POSID = gridSubItems.Items[index].FindControl("POSID") as Label;


                if (index != i)
                {
                    DataRow dr = dt.NewRow();                 
                    dr["AccessoryID"] = AccessoryID.Text;
                    dr["AccessoryCompanyNum"] = AccessoryCompanyNum.Text;
                    dr["AccessoryName"] = AccessoryName.Text;
                    dr["Unit"] = Unit.Text;
                    dr["Count"] = Count.Text;
                    dr["StockSource"] = StockSource.Text;
                    dr["POSID"] = POSID.Text;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        //订单明细to stock
        private void POSToStock(string POID)
        {
            string whereSql = " and IsClose='0' and POID ='" + POID + "'";
            DataTable dtPO = new StockBll().QueryAccessoryPO(whereSql);
            DataTable dt = new AccessoryInfo().getAccessoryInfoStructure();
            for (int index = 0; index < dtPO.Rows.Count; index++)
            {
                if (dtPO.Rows[index]["IsClose"].ToString() == "0")
                {
                    DataRow dr = dt.NewRow();
                    dr["POSID"] = dtPO.Rows[index]["POSID"];
                    dr["AccessoryID"] = dtPO.Rows[index]["AccessoryID"];
                    dr["AccessoryCompanyNum"] = dtPO.Rows[index]["AccessoryCompanyNumber"];
                    dr["AccessoryName"] = dtPO.Rows[index]["AccessoryName"];
                    dr["Unit"] = dtPO.Rows[index]["Unit"];
                    dr["Count"] =Convert.ToDecimal(dtPO.Rows[index]["Quantity"]) - Convert.ToDecimal(dtPO.Rows[index]["QuantityInStock"]);
                    dt.Rows.Add(dr);
                }
            }
            gridSubItems.DataSource = dt;
            gridSubItems.DataBind();
        }

        //订单主信息to stock
        private void POToStock(string POID)
        {
            string whereSql = " and POID ='" + POID + "'";
            string stockType;
            DataTable dtPO = new StockBll().QueryAccessoryPO(whereSql);
            if (dtPO.Rows.Count >0)
            {
                stockType = dtPO.Rows[0]["POType"].ToString();

                switch (stockType){
                    case "保内索赔":
                        StorckInType.SelectedValue="0";
                        break;
                    case "厂家采购":
                        StorckInType.SelectedValue = "1";
                        break;
                    case "外部采购":
                        StorckInType.SelectedValue = "2";
                        break;
                }
                supplyno.Text = dtPO.Rows[0]["PONO"].ToString();
            }
           
        }

        protected void link_saveBill_Click(object sender, EventArgs e)
        {
            
            string Maintainbillno = BusinessNum.Text.Trim();
            if (Maintainbillno !="" && new MaintainBillBll().IsExistsMaintainBill(Maintainbillno) == 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "sasa", "alert('输入的服务单据号不存在，请重新输入！')", true);
                return;
            }
            WsmAccessoryStockInEntity stockInEntity;
            if (StockInID != Guid.Empty)
            {
                stockInEntity = new SystemBll().Get<WsmAccessoryStockInEntity>(StockInID);
                try
                {
                    new SystemBll().Delete<WsmAccessoryStockEntity>(" and StockInID='" + StockInID + "'");
                }
                catch {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "sasa", "alert('明细中已有配件发生变更,入库单更改失败')", true);
                    return;
                }
            }
            else
            {
                stockInEntity = new WsmAccessoryStockInEntity();
                stockInEntity.BillCode = new StockBll().GetInBillCode();
                stockInEntity.StockInID = Guid.NewGuid();
                stockInEntity.CreatedBy = CurrentUserID;
                stockInEntity.CreatedOn = DateTime.Now;
               
                stockInEntity.InStockdate = InstockDate.SelectedDate.Value;
            }
        
            stockInEntity.BusinessNum = BusinessNum.Text.Trim();
            stockInEntity.Memo = Memo.Text;
            stockInEntity.supplyno = supplyno.Text;
            stockInEntity.Operator = new Guid(employeeGUID.Value);
            stockInEntity.StorckInType = System.Convert.ToInt32(StorckInType.SelectedValue);
            stockInEntity.StockinProperty = ddlStockinProperty.SelectedValue;
            stockInEntity.Deleted = false;
            new SystemBll().InsertOrUpdate(stockInEntity);
            for (int index = 0; index < gridSubItems.Items.Count; index++) {
                Label AccessoryID = gridSubItems.Items[index].FindControl("AccessoryID") as Label;
                Label AccessoryCompanyNum = gridSubItems.Items[index].FindControl("AccessoryCompanyNum") as Label;
                Label AccessoryName = gridSubItems.Items[index].FindControl("AccessoryName") as Label;
                Label Unit = gridSubItems.Items[index].FindControl("Unit") as Label;
                TextBox Count = gridSubItems.Items[index].FindControl("Count") as TextBox;
                Label StockSource = gridSubItems.Items[index].FindControl("StockSource") as Label;
                Label POSID = gridSubItems.Items[index].FindControl("POSID") as Label;

                for (int iIndex = 0; iIndex < System.Convert.ToInt64(System.Convert.ToDecimal(Count.Text)); iIndex++)
                {
                    WsmAccessoryStockEntity entity = new WsmAccessoryStockEntity();
                    entity.StockID = Guid.NewGuid();
                    entity.StockInID = stockInEntity.StockInID;
                    entity.AccessoryID = new Guid(AccessoryID.Text.Trim());
                    entity.AccessoryCode = new StockBll().GetAccessoryCode();
                    entity.CreatedBy = CurrentUserID;
                    entity.CreatedOn = DateTime.Now;
                    entity.AccessoryName = AccessoryName.Text;
                    entity.Unit = Unit.Text;
                    entity.AccessoryCompanyNum = AccessoryCompanyNum.Text;
                    entity.AccessoryStatus = System.Convert.ToInt32(Enumerator.AccessoryStatusInStock.InStock);
                    entity.CreateTime = DateTime.Now;
                    entity.Quantity = System.Convert.ToDecimal("1");
                    if (POSID.Text != "")
                    { entity.POSID = new Guid(POSID.Text); }
                    entity.StockSource = StockSource.Text;
                    new SystemBll().InsertOrUpdate(entity);
                    new MaintainBillBll().updateAccessoryReplacement(Maintainbillno, AccessoryID.Text.Trim());
                }
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "save", "alert('入库成功');window.close();", true);
        }
        protected void gridSubItems_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                gridSubItems.DataSource = getDateFromGrid(e.Item.ItemIndex);
                gridSubItems.DataBind();
            }
        }
        protected void gridSubItems_ItemDataBound(object sender, GridItemEventArgs e)
        {
           
        
        }
    }
}
